package cn.tedu.lucky.draw.server.service.impl;

import cn.tedu.lucky.draw.server.common.enums.DrawEnum;
import cn.tedu.lucky.draw.server.common.result.JsonResult;
import cn.tedu.lucky.draw.server.protocol.po.ActivityPrize;
import cn.tedu.lucky.draw.server.protocol.po.Prize;
import cn.tedu.lucky.draw.server.protocol.query.PrizeQuery;
import cn.tedu.lucky.draw.server.repository.ActivityPrizeRepository;
import cn.tedu.lucky.draw.server.repository.PrizeRepository;
import cn.tedu.lucky.draw.server.service.IPrizeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 服务层-奖品接口实现类
 */
@Service
public class PrizeService implements IPrizeService {
    @Autowired
    private PrizeRepository prizeRepository;
    private List<Prize> prizeList;

    @Autowired
    private ActivityPrizeRepository activityPrizeRepository;

    /**
     * 查询所有奖品
     */
    @Override
    public List<Prize> findAll(PrizeQuery prizeQuery) {
        if (prizeList == null) {
            prizeList = prizeRepository.findAll();
        }
        String name = prizeQuery.getName();
        Integer status = prizeQuery.getStatus();

        return prizeList.stream().filter(prize -> name == null || name.equals(prize.getName()) || name == "")
                .filter(prize -> status==null|| status.equals(prize.getStatus())).collect(Collectors.toList());
    }

    /**
     * 新增奖品
     */
    @Override
    public void save(Prize prize) {
        LocalDateTime now = LocalDateTime.now();
        prize.setCreateTime(now);
        prize.setUpdateTime(now);
        prizeRepository.save(prize);
        prizeList = null;
    }

    @Override
    public List<Prize> findPrizeByActivityId(Long id) {
        List<ActivityPrize> activityPrizes = activityPrizeRepository.findByActivityId(id);
        List<Long> prizeIds = activityPrizes.stream().map(ActivityPrize::getPrizeId).collect(Collectors.toList());
        List<Prize> prizes = prizeRepository.findAllById(prizeIds);
        return prizes;
    }

    @Override
    public List<Prize> findNoBindPrize(Long id) {
        //todo 1.先获取已绑定的奖品id
        // 2.再排除掉已绑定的商品id，剩下的就是未绑定的奖品
        List<ActivityPrize> activityPrizes = activityPrizeRepository.findByActivityId(id);
        List<Long> prizeIds = new ArrayList<>();
        for (ActivityPrize prize : activityPrizes) {
            prizeIds.add(prize.getPrizeId());
        }
        Integer status = Integer.valueOf(DrawEnum.ENABLE.getCode());
        //没有绑定的奖品，返回所有启用的奖品
        if (prizeIds.isEmpty()){
            return prizeRepository.findByStatusEquals(status);
        }
        return prizeRepository.findByIdNotInAndStatusEquals(prizeIds,status);
    }
}
